<?php
class Model_MapperAdresse implements Model_IMapper
{
	private $table = null;
	
	public function __construct($str_table, $pdo)
	{
		$this->table = new Model_TableAdresse();
		$this->table->setConnexion($pdo);
		$this->table->init();
	}
	
	public function getAll()
	{
		$results = array();
		foreach($this->table->fetchAll() as $ligne)
		{
			$entity = new Model_Adresse();
			$entity->setId_adresse($ligne['id_adresse']);
			$entity->setAdresse1($ligne['adresse1']);
			$entity->setAdresse2($ligne['adresse2']);
			
			//recupere la commune
			$communemap = new Model_MapperCommune("commune", $this->table->getConnexion());
			$commune = $communemap->getOne($ligne['id_commune']);
			
			if(!is_null($commune))
				$entity->setCommune($commune);
					
			$results[] = $entity;
		}
		return $results;
	}
	
	public function getOne($id)
	{
		$ligne = $this->table->fetchOne($id);
		if(!empty($ligne['id_adresse']) )
		{
			$entity = new Model_Adresse();
			$entity->setId_adresse($ligne['id_adresse']);
			$entity->setAdresse1($ligne['adresse1']);
			$entity->setAdresse2($ligne['adresse2']);
			
			//recupere la commune
			$communemap = new Model_MapperCommune("commune", $this->table->getConnexion());
			$commune = $communemap->getOne($ligne['id_commune']);
			
			if(!is_null($commune))
				$entity->setCommune($commune);
		}
		else 
		{
			$entity = null;
		}
		return $entity;
	}
	
	public function save(Model_IEntity $object)
	{
		if($object->getId_adresse() == -1)
		{
			$id = $this->table->insert($object->getAdresse1(), $object->getAdresse2(), $object->getCommune()->getId_commune());
			$object->setId_adresse($id);
		}
		else
		{
			$this->table->update($object->getId_adresse(), $object->getAdresse1(), $object->getAdresse2(), $object->getCommune()->getId_commune());
		}
	}
	
	public function delete(Model_IEntity $object)
	{
		$this->table->delete($object->getId_adresse());
	}
}